var express = require('express');
var router = express.Router();
const {
    UserModel, DingTableModel,
    NoticeTableModel, Rusult,
    SpecialModel, DailyModel,
    RepairModel } = require('../model/csy/index')
const jwt = require('jsonwebtoken');
const QRCode = require('qrcode')

const tencentcloud = require("tencentcloud-sdk-nodejs-iai");

global.require = require;
//调用sdk短信
const SMSClient = require('@alicloud/sms-sdk');
/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', { title: 'Express' });
});

const token = 'weiwei'

// 注册用户
router.post('/register', async (req, res) => {
    const { phone, password } = req.body;
    //验证手机号格式
    const phonePattern = /^1[3-9]\d{9}$/;
    if (!phonePattern.test(phone)) {
        res.send({
            code: 400,
            msg: '手机号格式不正确'
        })
    } else {
        try {
            await UserModel.create({ phone: phone, password: password });
            res.send({
                code: 200,
                msg: '注册成功'
            })
        } catch (error) {
            console.error('Registration error:', error);
            res.status(500).json({ message: 'Internal server error' });
        }
    }
})

// 登录
router.post('/login', async (req, res) => {
    const { phone, password } = req.body;
    console.log(phone);
    try {
        const user = await UserModel.findOne({ phone: phone, password: password });
        if (!user) {
            res.send({
                code: 404,
                msg: '用户不存在'
            })
        } else {
            const userInfo = {
                userName: user.phone
            }
            //生成一个唯一的sessionToken
            const accessToken = jwt.sign(userInfo, token, { expiresIn: '0.5h' });
            const refreshToken = jwt.sign(userInfo, token, { expiresIn: '7d' });

            //将sessionToken存入数据库
            await UserModel.updateOne({ phone: phone }, { $set: { assect_token: accessToken, refach_token: refreshToken } });
            res.send({
                code: 200,
                msg: '登录成功',
                data: {
                    data: user,
                    accessToken,
                    refreshToken
                }
            })
        }
    } catch (error) {
        console.error('Login error:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
})

//刷新Token
router.post('/refresh', (req, res) => {
    const token1 = req.body.params.token
    let userName = '';
    try {
        const userInfo = jwt.verify(token1, token);
        console.log(userInfo);

        userName = userInfo.userName;
    } catch (err) {
        res.send({
            code: 401,
            msg: 'token过期'
        })
    }
    const userInfo = {
        userName
    }
    console.log(userName);
    const accessToken = jwt.sign(userInfo, token, { expiresIn: '0.5h' });
    const refreshToken = jwt.sign(userInfo, token, { expiresIn: '7d' });
    UserModel.updateOne({ phone: userName }, { $set: { assect_token: accessToken, refach_token: refreshToken } }).then(rep => {
        res.send({
            code: 200,
            msg: '刷新成功',
            data: {
                accessToken,
                refreshToken
            }
        })
    })
})



//发送短信验证码
router.post('/sendCode', function (req, res, next) {
    const { phone } = req.body;
    // 生成随机验证码
    const code = Math.floor(Math.random() * 9000 + 1000);
    // 验证手机号格式
    const phonePattern = /^1[3-9]\d{9}$/;
    if (!phonePattern.test(phone)) {
        return res.send({
            code: 400,
            msg: '手机号格式不正确'
        });
    }
    let smsClient = new SMSClient({
        accessKeyId: 'LTAI5tJu15bFh4iGGUAkkin1',
        secretAccessKey: 'wtbmNQGpGLYBvY2GGmZTKuBShsP615',
    });
    // 开始发送短信
    smsClient.sendSMS({
        PhoneNumbers: phone,
        SignName: '医治',
        TemplateCode: 'SMS_478560519',
        TemplateParam: `{ "code": "${code}" }` // 短信模板变量
    }).then(function (result) {
        console.log(result);
        let { Code } = result;
        if (Code === 'OK') {
            // 发送成功后返回响应
            return res.send({
                code: 200,
                msg: '发送成功',
                data: code
            });
        }
    }).catch(function (err) {
        console.log(err); // 打印错误信息，方便调试
        return res.send({
            code: 500,
            msg: '发送失败'
        });
    });
});

const axios = require('axios')
const querystring = require('querystring')

//配置
const host = "https://gyytz.market.alicloudapi.com"
const path = "/sms/smsSend";
const appcode = "bd737d96c048443facd8d40252162d8e"; // 替换为你的 AppCode
const smsSignId = "2e65b1bb3d054466b82f0c9d125465e2";
const templateId = "908e94ccf08b4476ba6c876d13f084ad";

//国阳云短信
router.post('/send-sms', async (req, res) => {
    const { mobile } = req.body; // 从请求体中获取手机号和验证码信息

    const phonePattern = /^1[3-9]\d{9}$/;
    if (!phonePattern.test(mobile)) {
        return res.send({
            code: 400,
            msg: '手机号格式不正确'
        });
    }
    if (!mobile) {
        return res.status(400).json({ error: "Missing required fields" });
    }
    const code = Math.floor(Math.random() * 9000 + 1000);
    const param = `**code**:${code},**minute**:5`;
    // 设置请求头
    const headers = {
        'Authorization': 'APPCODE ' + appcode,
        'Content-Type': 'application/x-www-form-urlencoded',
    };

    // 设置查询参数
    const queryParams = querystring.stringify({
        mobile: mobile,
        param: param,
        smsSignId: smsSignId,
        templateId: templateId,
    });
    try {
        // 发送 POST 请求
        const response = await axios.post(`${host}${path}`, queryParams, { headers });
        // 返回响应数据
        res.json({
            code: 200,
            data: code

        });
    } catch (error) {
        console.error('Error sending SMS:', error);
        res.status(500).json({ error: 'Failed to send SMS' });
    }
});


//生成二维码
router.post('/createQRCode', function (req, res, next) {
    // const data = req.body
    //生成一个唯一的sessionToken
    const sessionToken = jwt.sign({ uniqueId: Date.now() }, token, { expiresIn: '15m' });
    QRCode.toDataURL(sessionToken, (err, url) => {
        res.send({
            code: 200,
            msg: '生成成功',
            data: url,
            sessionToken: sessionToken

        })
    })
})

//验证二维码
router.post('/verifyQRCode', function (req, res, next) {
    const { sessionToken } = req.body; // 从请求中获取sessionToken

    if (!sessionToken) {
        return res.status(400).send({
            code: 400,
            msg: '缺少sessionToken'
        });
    }

    // 验证JWT
    jwt.verify(sessionToken, token, function (err, decoded) {
        if (err) {
            // 如果验证失败（如过期或无效）
            return res.status(401).send({
                code: 401,
                msg: '二维码验证失败',
                error: err.message
            });
        }

        // 如果验证成功，返回解码后的信息（如 uniqueId）
        res.send({
            code: 200,
            msg: '二维码验证成功',
            data: decoded
        });
    });
});

//验证码登录
router.post('/yzmLogin', async (req, res, next) => {
    const { phone } = req.body;
    if (!phone) {
        return res.send({
            code: 400,
            msg: '手机号不能为空'
        });
    }
    //查看数据库中是否存在该手机号
    const user = await UserModel.findOne({ phone: phone });
    if (!user) {
        return res.send({
            code: 400,
            msg: '该手机号未注册'
        });
    }
    const userInfo = {
        phone: user.phone
    }
    const accessToken = jwt.sign(userInfo, token, { expiresIn: '0.5h' });
    const refreshToken = jwt.sign(userInfo, token, { expiresIn: '7d' });
    //将refreshToken存入数据库
    await UserModel.updateOne({ phone: phone }, { $set: { assect_token: accessToken, refach_token: refreshToken } }).then(rea => {
        res.send({
            code: 200,
            msg: '登录成功',
            data: {
                data: user,
                accessToken,
                refreshToken
            }
        });
    })
});

//修改密码
router.post('/updatePassword', async (req, res, next) => {
    const { phone, password } = req.body;
    if (!phone || !password) {
        return res.send({
            code: 400,
            msg: '手机号或密码不能为空'
        });
    }
    //查看数据库中是否存在该手机号
    const user = await UserModel.findOne({ phone: phone });
    if (!user) {
        return res.send({
            code: 400,
            msg: '该手机号未注册'
        });
    }
    //修改密码
    await UserModel.updateOne({ phone: phone }, { $set: { password: password } }).then(rea => {
        res.send({
            code: 200,
            msg: '修改成功'
        })
    })
})

//初始化人脸识别客户端
const IaiClient = tencentcloud.iai.v20200303.Client;
const clientConfig = {
    credential: {
        secretId: "AKIDZ0Vu7v78ya3KOURBh071kGYgcKp7B1tb",
        secretKey: "d7PaYMxQrDRWPI2Z4PYTBh3DAuTs7E7p",
    },
    region: "ap-beijing",
    profile: {
        httpProfile: {
            endpoint: "iai.tencentcloudapi.com",
        },
    },
};

// 实例化人脸识别客户端
const client = new IaiClient(clientConfig);

//让用户和人脸库进行绑定
router.post('/faceBind', async (req, res) => {
    let b64 = req.body.base64;  // 获取传入的 Base64 图像数据
    let phone = req.body.phone;  // 获取传入的手机号
    // 确保去掉头部信息
    b64 = b64.replace(/^data:image\/\w+;base64,/, ""); // 去掉图像数据的头部标识
    // 设置调用 API 的参数
    const params = {
        'GroupIds': ['Csy_face'],  // 替换为实际有效的人员库ID
        'Image': b64,
        'NeedPersonInfo': 1,
        'QualityControl': 0,
        'FaceMatchThreshold': 85,
    };
    try {
        // 调用人脸识别 API，并等待其结果
        const data = await client.SearchFaces(params);
        // 检查 API 返回的数据
        if (data && data.Results[0].Candidates[0].FaceId) {
            //将人脸id和手机号存入数据库
            UserModel.updateOne({ phone: phone }, { faceId: data.Results[0].Candidates[0].FaceId }).then(rep => {
                res.send({
                    code: 200,
                    message: "人脸绑定成功",
                })
            })
        } else {
            res.send({
                code: 404,
                message: "人脸绑定失败",
            });
        }
    } catch (err) {
        res.send({
            code: 500,
            message: "服务器错误",
        });
    }
})

// 蔡森源人脸登录
router.post('/faceLogin', async (req, res) => {
    let b64 = req.body.base64;  // 获取传入的 Base64 图像数据
    // 确保去掉头部信息
    b64 = b64.replace(/^data:image\/\w+;base64,/, "");  // 去掉图像数据的头部标识
    // 设置调用 API 的参数
    const params = {
        'GroupIds': ['Csy_face'],  // 替换为实际有效的人员库ID
        'Image': b64,
        'NeedPersonInfo': 1,
        'QualityControl': 0,
        'FaceMatchThreshold': 85,
    };
    try {
        // 调用人脸识别 API，并等待其结果
        const data = await client.SearchFaces(params);
        // 检查 API 返回的数据
        if (data && data.Results && data.Results.length > 0) {
            // 如果有匹配的结果
            UserModel.findOne({ faceId: data.Results[0].Candidates[0].FaceId }).then(rep => {
                //  登录成功后把长短token更新到数据库
                const userInfo = { phone: rep.phone };
                const accessToken = jwt.sign(userInfo, token, { expiresIn: '0.5h' });
                const refreshToken = jwt.sign(userInfo, token, { expiresIn: '7d' });
                UserModel.updateOne({ _id: rep._id }, { $set: { assect_token: accessToken, refach_token: refreshToken } }).then(rea => {
                    if (rea) {
                        res.send({
                            code: 200,
                            message: "人脸登录成功",
                            data: {
                                data: rep,
                                accessToken: accessToken,
                                refreshToken: refreshToken
                            },
                        })
                    } else {
                        res.send({
                            code: 404,
                            message: "人脸登录失败",
                        });
                    }
                })
            })
        } else {
            // 如果没有匹配的结果
            res.send({
                code: 404,
                message: "未找到匹配的人脸",
            });
        }
    } catch (err) {
        // 捕获并处理错误
        console.error("Error occurred while calling SearchFaces:", err);  // 打印错误信息
        res.send({
            code: 500,
            message: "API 调用失败",
            details: err.message || err,  // 返回详细的错误信息
        });
    }
});

//定期检查
router.post('/setdingTable', async (req, res) => {
    let data = req.body
    console.log(data);

    DingTableModel.create(data).then(rep => {
        res.send({
            code: 200,
            message: "添加成功",
        })
    })
})

//回显列表
router.get('/getdingTable', async (req, res) => {
    const { page } = req.query
 
    // 实现分页
    DingTableModel.find().skip((page - 1) * 5).then(rep => {
        res.send({
            code: 200,
            message: "查询成功",
            data: rep
        })
    })
})


//添加通知单
router.post('/setNoticeTable', async (req, res) => {
    let data = req.body
    NoticeTableModel.create(data).then(rep => {
        res.send({
            code: 200,
            message: "添加成功",
        })
    })
})


var multiparty = require('multiparty');
//添加文件
router.post('/upload', async (req, res) => {
    var form = new multiparty.Form({
        uploadDir: './uploads', // 设置文件上传目录
    });
    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log('parse error: ' + err);
            res.send({
                code: 500,
                message: "上传失败",
            });
        } else {
            res.send({
                code: 200,
                message: "上传成功",
                data: 'http://localhost:3000/uploads/' + files.file[0].path
            })
        }
    });
})

//添加结果报告
router.post('/setRusult', async (req, res) => {
    let data = req.body
    Rusult.create(data).then(rep => {
        res.send({
            code: 200,
            message: "添加成功",
        })
    })
})

//添加特别检查
router.post('/setSpecial', async (req, res) => {
    let data = req.body
    SpecialModel.create(data).then(rep => {
        res.send({
            code: 200,
            message: "添加成功",
        })
    })
})

//回显特别检查
router.get('/getSpecial', async (req, res) => {
    SpecialModel.find().then(rep => {
        res.send({
            code: 200,
            message: "查询成功",
            data: rep
        })
    })
})

//添加日常维修
router.post('/setDaily', async (req, res) => {
    let data = req.body
    DailyModel.create(data).then(rep => {
        res.send({
            code: 200,
            message: "添加成功",
        })
    })
})

//回显日常维修
router.get('/getDaily', async (req, res) => {
    DailyModel.find().then(rep => {
        res.send({
            code: 200,
            message: "查询成功",
            data: rep
        })
    })
})


//添加维修结果
router.post('/setRepair', async (req, res) => {
    let data = req.body
    RepairModel.create(data).then(rep => {
        //添加维修结果后并把DailyModel的state改为待审核   
        DailyModel.updateOne({ _id: data.daily }, { state: '待审核' }).then(rep => {
            res.send({
                code: 200,
                message: "添加成功",
            })
        })
    })
})
//查看单一审核内容  
router.post('/getRepair', async (req, res) => {
    let data = req.body
    DailyModel.findOne({ _id: data.daily }).then(rep => {
        res.send({
            code: 200,
            message: "查询成功",
            data: rep
        })
    })
})

//修改DailyModel中state状态
router.post('/setDailyState', async (req, res) => {
    let data = req.body

    DailyModel.updateOne({ _id: data.id }, { state: data.state }).then(rep => {
        res.send({
            code: 200,
            message: "修改成功",
            data: rep
        })
    })
})
//删除日常维修
router.post('/delDaily', async (req, res) => {
    let data = req.body
    DailyModel.deleteOne({ _id: data.id }).then(rep => {
        res.send({
            code: 200,
            message: "删除成功",
            data: rep
        })
    })
})

//删除特别检查
router.post('/delSpecial', async (req, res) => {
    let data = req.body
    SpecialModel.deleteOne({ _id: data.id }).then(rep => {
        res.send({
            code: 200,
            message: "删除成功",
            data: rep
        })
    })
})
//删除定期检查
router.post('/delDing', async (req, res) => {
    let data = req.body
    DingTableModel.deleteOne({ _id: data.id }).then(rep => {
        res.send({
            code: 200,
            message: "删除成功",
            data: rep
        })
    })
})



router.post('/captcha', async (req, res) => {

    const host = 'https://fscaptcha.market.alicloudapi.com';
    const appcode = 'bd737d96c048443facd8d40252162d8e';  // 记得替换成你自己的 AppCode
    // 你需要传递的请求参数
    const bodys = {
        CaptchaAppId: '192076471',
        AppSecretKey: 'HiBoyhfwXbjbdPq0GMZMzxywt',
        RandStr: '!@v32',
        Ticket: 'Efs3o2dsVdwEfs3o2dsVdwEfs3o2dsVdwEfs3o2dsVdwEfs3o2dsVdw',
        UserIp: '53.70.12.13',
    };

    try {
        // 发送请求
        const response = await axios.post(host, new URLSearchParams(bodys), {
            headers: {
                'Authorization': `APPCODE ${appcode}`,
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
        });
        // 返回响应数据
        res.json(response.data);
    } catch (error) {
        console.error('请求失败', error);
        res.status(500).json({ error: '请求失败', details: error.message });
    }
});




module.exports = router;
